package com.qdu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qdu.commons.RedisKey;
import com.qdu.commons.Result;
import com.qdu.entity.Mytrace;
import com.qdu.entity.Route;
import com.qdu.entity.RouteTrace;
import com.qdu.entity.User;
import com.qdu.service.impl.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import java.awt.peer.SystemTrayPeer;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ellery2018
 * @since 2022-03-09
 */
@Slf4j
@RestController
@RequestMapping("/complete")
public class CompleteController {


    @Autowired
    UserServiceImpl userService;
    @Autowired
    CompleteServiceImpl completeService;
    @Autowired
    MytraceServiceImpl mytraceService;



    @Autowired
    RouteTraceServiceImpl routeTraceService;

    @PostMapping("/usepower")
    public Result usepower(@RequestParam("id") Integer userid, @RequestParam("routeid") Integer routeid) {

        User user = userService.getById(userid);
        Integer nowpower = user.getHealthPower();
        System.out.println(nowpower);
        Result result = new Result();
        if (nowpower < 350000) {
            return Result.FAIL();
        } else {
            userService.updateHealthPower(userid, 350000);
            completeService.onlinesign(routeid, userid);
            return Result.SUCCESS();
        }

    }

    @PostMapping("/refresh")
    @ApiOperation(value = "每次进入页面删除用户未完成的健步行记录")
    public void refresh(@RequestParam("userid") Integer userid) {
        completeService.refresh(userid);
    }




    @Autowired
    RouteServiceImpl routeService;

    @PostMapping("/signstart")
    @ApiOperation(value = "起点打卡")
    public Result signStart(@RequestParam("longitude") String longitude, @RequestParam("latitude") String latitude, @RequestParam("routeid") Integer routeid, @RequestParam("userid") Integer userid,@RequestParam("beginLongitude") String beginLongitude, @RequestParam("beginLatitude") String beginLatitude) {
        return Result.SUCCESS();
//        Double lo1 = Double.parseDouble(longitude);
//        Double la1 = Double.parseDouble(latitude);
//        Double lo2 = Double.parseDouble(beginLongitude);
//        Double la2 = Double.parseDouble(beginLatitude);
//
//        Double nowdistance = completeService.getDistance(lo1, la1, lo2, la2);
//        if (nowdistance < 501.0) {
//            log.info("起点打卡成功，当前距离"+nowdistance+"精度500m");
//            completeService.startsign(userid, routeid);
//            return Result.SUCCESS();
//        } else {
//            System.out.println(Result.FAIL().getCode());
//            return Result.FAIL();
//        }

    }

//    @PostMapping("/signend")
//    @ApiOperation(value = "终点打卡")
//    public Result signEnd(@RequestParam("longitude") String longitude, @RequestParam("latitude") String latitude, @RequestParam("routeid") Integer routeid, @RequestParam("userid") Integer userid) {
//
//
//        User user = userService.getById(userid);
//        Route route = routeService.getById(routeid);
//
//        System.out.println(longitude + "**********************+" + latitude + "*********************");
//
//
//        Double lo1 = Double.parseDouble(longitude);
//        Double la1 = Double.parseDouble(latitude);
//        Double lo2 = Double.parseDouble(route.getEndLong());
//        Double la2 = Double.parseDouble(route.getEndLat());
//
//
//        System.out.println(lo1 + "*********" + la1 + "*************+" + lo2 + "*********************" + la2);
//        Double nowdistance = completeService.getDistance(lo1, la1, lo2, la2);
//        if (nowdistance < 501.0) {
//            if (completeService.endsign(userid, routeid) == false) return Result.SUCCESS("nostartsign");
//            return Result.SUCCESS();
//        } else {
//            return Result.FAIL();
//        }
//
//    }

    @PostMapping("/addTrace")
    @ApiOperation(value = "将轨迹信息添加到数据库中")
    public void addTrace(@RequestBody List<Mytrace> myTraces) {
        mytraceService.saveBatch(myTraces);
    }

    @GetMapping("/isDone/{scenicId}/{userId}")
    @ApiOperation(value = "当前景点用户是否完成打卡")
    public Result isDone(@PathVariable("scenicId") int scenicId, @PathVariable("userId") int userId) {
        Integer state= completeService.findstate(userId,scenicId);
        if(state == 2 || state == 3) return  Result.SUCCESS(true);
        else return Result.SUCCESS(false);
    }

    @GetMapping("/findComplete")
    @ApiOperation(value = "当前用户打卡完成情况")
    public Result findComplete(int userId) {
        return Result.SUCCESS(completeService.findListByUId(userId));
    }

    @PostMapping("/ifleave")
    @ApiOperation(value = "判断是否偏离路线")
    public Result ifleave(@RequestParam("longitude") String longitude, @RequestParam("latitude") String latitude, @RequestParam("routeid") Integer routeid, @RequestParam("userid") Integer userid) {

        List<RouteTrace> routeTraces;

        if (redisTemplate.hasKey(RedisKey.ROUTE_TRACE+routeid)){
             routeTraces = redisTemplate.opsForList().range(RedisKey.ROUTE_TRACE+routeid, 0, -1);
        }else{
             routeTraces  = routeTraceService.list(new QueryWrapper<RouteTrace>().eq("routeId",routeid).orderByAsc("routeTraceId"));

        }



        System.out.println(routeTraces.toString());

        boolean hasleave=true;
        for(int i = 0;i<routeTraces.size();i++){
            RouteTrace tem= routeTraces.get(i);
            Double lo = Double.parseDouble(longitude);
            Double la = Double.parseDouble(latitude);
            Double la1 = Double.parseDouble(tem.getLatitude());
            Double lo1 = Double.parseDouble(tem.getLongitude());
            if(completeService.getDistance2(lo1, la1, lo, la) < 100.1){
                log.info("当前未偏移，距离"+completeService.getDistance2(lo1, la1, lo, la)+"精度100m");
                hasleave = false;
                break;
            }
        }

            long t1=System.currentTimeMillis();
            if(hasleave == true){
                log.info("路线偏移！！！！！！！！！！！！！！！！！！！！！！！！！！！！！"+t1);
                return Result.SUCCESS(t1); //已偏离路线
            }
            else{
                return Result.FAIL(); //未偏离路线
            }


    }

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/ifEnd")
    @ApiOperation(value = "自动终点打卡")
    public Result ifEnd(@RequestParam("longitude") String longitude, @RequestParam("latitude") String latitude, @RequestParam("routeid") Integer routeid, @RequestParam("userid") Integer userid,@RequestParam("endLongitude") String endLongitude, @RequestParam("endLatitude") String endLatitude) {


        Double lo1 = Double.parseDouble(longitude);
        Double la1 = Double.parseDouble(latitude);
        Double lo2 = Double.parseDouble(endLongitude);
        Double la2 = Double.parseDouble(endLatitude);


        Double nowdistance = completeService.getDistance(lo1, la1, lo2, la2);
        if (nowdistance < 501.0) {
            if (completeService.endsign(userid, routeid) == false){
                userService.completeGetPoint(userid);
                return Result.SUCCESS("nostartsign");
            }
            return Result.SUCCESS();
        } else {
            return Result.FAIL();
        }
    }

    @PostMapping("/findphotostate")
    @ApiOperation(value = "查询照片审核状态")
    public String findPhotoState(@RequestParam("id") Integer userid,@RequestParam("routeId") Integer routeid) {
        return completeService.findphotosign(userid,routeid);
    }
}